#!/usr/bin/env python

"""
Small example script to drive the api.snmp query objects.
"""

import calendar
import datetime
import json
import os
import pprint
import requests
import sys
import time
import warnings

from optparse import OptionParser

from esmond.api.client.snmp import ApiConnect, ApiFilters

def main():
    import os.path
    from optparse import OptionParser
    usage = '%prog [ -v | -U api_url ]'
    parser = OptionParser(usage=usage)
    parser.add_option('-U', '--url', metavar='ESMOND_REST_URL',
            type='string', dest='api_url',
            help='URL for the REST API (default=%default).',
            default='localhost')
    parser.add_option('-l', '--last', metavar='LAST',
            type='int', dest='last', default=0,
            help='Last n minutes of data to query.')
    parser.add_option('-d', '--device', metavar='DEVICE',
            type='string', action='store',
            default=None, dest='device',
            help='Device name to filter - can also be a pattern (ex: lbl-).')
    parser.add_option('-i', '--interface', metavar='INTERFACE',
            type='string', dest='interface',
            help='Interface name to filter - can also be a pattern (ex: lo.')
    parser.add_option('-u', '--user', metavar='USER',
            type='string', dest='user', default='',
            help='POST interface username.')
    parser.add_option('-k', '--key', metavar='API_KEY',
            type='string', dest='key', default='',
            help='API key for post operation.')
    parser.add_option('-v', '--verbose',
                dest='verbose', action='count', default=False,
                help='Verbose output - -v, -vv, etc.')
    options, args = parser.parse_args()

    filters = ApiFilters()

    filters.verbose = options.verbose

    if options.last:
        filters.begin_time = int(time.time() - (options.last*60))

    if options.device:
        device_filters = {"name": options.device}
    else:
        device_filters = {}

    if options.interface:
        interface_filters = {'ifDescr': options.interface}
    else:
        interface_filters = {}

    conn = ApiConnect(options.api_url, filters, username=options.user,
        api_key=options.key)

    # return 1

    for d in conn.get_devices(**device_filters):
        print d
        # print d.dump
        print '  *', d.begin_time, '|', d.end_time, '|', d.oidsets
        for i in d.get_interfaces(**interface_filters):
            print '  ', i, i.begin_time
            for e in i.get_endpoints():
                print '   *', e
                print '     +', e.get_data().dump
        break
    pass

if __name__ == '__main__':
    main()
